//
//  QianliCountryVC.swift
//  todoios
//
//  Created by qianli on 2025/4/15.
//

import Foundation
import UIKit
import SwiftyUserDefaults
import Yams

class QianliCountryVC: QianliParentNaviVC {
    private var Hvq8YW7v25bbqUMo:UIButton=UIButton()
    private var QuV46HvbGc1uLhUB:UIButton=UIButton()
    private var F04Jpss3hC2aRHCt:UIButton=UIButton()
    private var bfLRcdX6OfQEmA24:[String] = []
    private var gbg6hniAI7KHgJ8B:MBProgressHUD?
    private var ARS0bJbeW0vnEMLd:UIButton?
    private var Y7sa3i82qEEkE5Uo:String = ""
    
    var invalid40101Block:((_ errMsg:String) -> Void)?
    
    lazy var nodeTable: UITableView = {
        let table = UITableView()
        return table
    }()
    
    private var DzKXzGjYZ3Z78P0n:UIView?
    
    deinit {
        QianliUniversalFunc.QianliLog("------QianliCountryVC.deinit")
    }
    
    override func aB7kFqI8MB6DRPQC() {
        let level = Defaults[\.memberLevel] //2为高级
        let serverState = Defaults[\.serviceStatus]
        let subState = Defaults[\.subStatus]
        if level == 2 && serverState && subState{
            cUYJyQbeBDg1Ukke();
        }else{
            //判断是否为未过期的高级会员，如果是从config.yaml中读取节点
            //如果不是从getNodeNames读取全部节点
            aEasv06wgYeX2ZHn();
        }
        IHVKcX5W6hwWzkw7()
    }
    
    
    override func GHL4Rhb91XYBer27(){
        self.zdMpsGrNncVEHdYA(title: LocalizedString("CHANGE REGION"))
        //右上解加个刷新按钮，当用户信息出错时才显示，点击可以重新加载用户信息
        self.ARS0bJbeW0vnEMLd = UIButton(frame: CGRect(x: qianli_pm_width-25-24, y: self.topSpace-46/2-24/2, width: 24, height: 24))
        if let freshBtn = self.ARS0bJbeW0vnEMLd{
            self.view.addSubview(freshBtn)
            freshBtn.qianli_button_image(image: "qianli_refresh_user".qianli_R_image,imgSize: CGSize(width: 24, height: 24),imgColor: .label)
            freshBtn.touch_With_Block { [weak self] sender in
                if let self = self{
                    QianliVibrateEnum.selection.L4smXfL531Hmh91R()
                    self.aB7kFqI8MB6DRPQC()
                }
            }
        }
        
//-----开关
        let switchRowHeight = 50.0
        let switchView = UIView(frame: CGRect(x: 15, y: topSpace+15, width: qianli_pm_width-30, height: switchRowHeight))
        self.view.addSubview(switchView)
        switchView.backgroundColor = .systemBackground
        switchView.layer.cornerRadius = 10
        let btnWidth = 100.0
        
        switchView.addSubview(self.Hvq8YW7v25bbqUMo)
        self.Hvq8YW7v25bbqUMo.frame = CGRect(x: 0, y: 0, width: btnWidth, height: switchRowHeight)
        self.Hvq8YW7v25bbqUMo.setTitle(LocalizedString("PAC PROXY"), for: .normal) //智能代理
        self.Hvq8YW7v25bbqUMo.setTitleColor(.secondaryLabel, for: .normal)
        self.Hvq8YW7v25bbqUMo.titleLabel?.font = .systemFont(ofSize: 15)
        
        switchView.addSubview(self.QuV46HvbGc1uLhUB)
        self.QuV46HvbGc1uLhUB.frame = CGRect(x: switchView.bounds.width-btnWidth, y: 0, width: btnWidth, height: switchRowHeight)
        self.QuV46HvbGc1uLhUB.setTitle(LocalizedString("GLOBAL PROXY"), for: .normal)//全局代理
        self.QuV46HvbGc1uLhUB.setTitleColor(.secondaryLabel, for: .normal)
        self.QuV46HvbGc1uLhUB.titleLabel?.font = .systemFont(ofSize: 15)
      
        
        let switchBarWidth = 40.0
        let switchBarHeight = 24.0
        let switchBar = UIView(frame: CGRect(x: switchView.bounds.width/2 - switchBarWidth/2, y: switchRowHeight/2-switchBarHeight/2, width: switchBarWidth, height: switchBarHeight))
        switchView.addSubview(switchBar)
        switchBar.tap_With_Block {[weak self] in
            self?.c6xbIZ9eThHGB1bP()
        }
        
        let switchBgHeight = 12.0
        let switchBg = UIView(frame: CGRect(x: 0, y: switchBarHeight/2-switchBgHeight/2, width: switchBarWidth, height: switchBgHeight))
        switchBar.addSubview(switchBg)
        switchBg.backgroundColor = .lightGray
        switchBg.layer.cornerRadius = switchBgHeight/2
        
        switchBar.addSubview(self.F04Jpss3hC2aRHCt)
        self.F04Jpss3hC2aRHCt.frame = CGRect(x: 0, y: 0, width: switchBarHeight, height: switchBarHeight)
        self.F04Jpss3hC2aRHCt.setImage("qianli_node_switchbtn".qianli_R_image, for: .normal)
        self.F04Jpss3hC2aRHCt.backgroundColor =  UIColor("#3366FF")
        self.F04Jpss3hC2aRHCt.layer.cornerRadius = switchBarHeight/2
        self.F04Jpss3hC2aRHCt.touch_With_Block { [weak self] sender in
            self?.c6xbIZ9eThHGB1bP()
        }
        
        
        let imode = Qianli_G_SharedMdb.shared.GetTunMode()
        if ("global"==imode){
            self.Hvq8YW7v25bbqUMo.setTitleColor(.secondaryLabel, for: .normal)
            self.QuV46HvbGc1uLhUB.setTitleColor(.label, for: .normal)
            self.F04Jpss3hC2aRHCt.frame = CGRect(x: switchBarWidth-switchBarHeight, y: 0, width: switchBarHeight, height: switchBarHeight)
        }else{
            self.Hvq8YW7v25bbqUMo.setTitleColor(.label, for: .normal)
            self.QuV46HvbGc1uLhUB.setTitleColor(.secondaryLabel, for: .normal)
            self.F04Jpss3hC2aRHCt.frame = CGRect(x: 0, y: 0, width: switchBarHeight, height: switchBarHeight)
        }
        let iTop = switchView.frame.maxY+15
        let nodeView = UIView(frame: CGRect(x: 0, y: iTop, width: qianli_pm_width, height: qianli_pm_height-iTop-UIDevice.qianli_bottom_safe_distance()))
        self.view.addSubview(nodeView)
        
        nodeView.addSubview(self.nodeTable)
        nodeTable.frame = CGRect(x: 0, y: 0, width: nodeView.bounds.width, height: nodeView.bounds.height)
        nodeTable.delegate = self
        nodeTable.dataSource = self
//        nodeTable.separatorStyle = .singleLine //默认即为singleLine
        nodeTable.separatorStyle = .none
        nodeTable.register(NodeItemCell.self, forCellReuseIdentifier: "NodeItemCell")
        nodeTable.backgroundColor = .secondarySystemBackground
    }
    
    private func aEasv06wgYeX2ZHn(){
//非有效的高级会员
        let memberLever = Defaults[\.memberLevel]
        if memberLever == 2{
            vFuidwaT3K4CZ0P6() //订阅节与yaml相同，只是没有流量及时间节点
        }else{
            //非高级会员，getNodeNames拉取全部
            self.M62h1bVOydwY8i4y("")
            LoginViewModel.shared.ZPu2bfdDaaLbgpbM {result in
                DispatchQueue.main.async {[weak self]  in
                    switch result{
                    case .failure(let error):
                        self?.IJrfj9ZrfY4QdGJ3(error.localizedDescription)
                    case .success(let baseData):
                        if baseData.code == 0{
                            self?.IJrfj9ZrfY4QdGJ3("")
                        }else{
                            self?.IJrfj9ZrfY4QdGJ3("[\(baseData.code)]\(baseData.msg)")
                        }
                    }
                }
            }
        }
        
    }
    
    private func IJrfj9ZrfY4QdGJ3(_ errmsg:String){
        self.l0JOXR3PG9RznwqZ()
        if errmsg.isEmpty{
            if let _ = LoginViewModel.shared.nodeNames{
                vFuidwaT3K4CZ0P6()//获取已订阅节点，比yaml中少了流量及到期节点
            }else{
                self.view.Qianli_Toast(LocalizedString("Node data not obtained, please try again later"))
            }
        }else{
            self.view.Qianli_Toast(errmsg)
        }
    }
    
    
    
    private func flM9woQKzM3ymMZp(_ errMsg:String){
        //表示登录失效，退出登录，清空信息，显示登录UI
        self.clFi25NuDNbscWXL()
        self.invalid40101Block?(errMsg)
    }
    
    private func c6xbIZ9eThHGB1bP(){
        QianliVibrateEnum.light.L4smXfL531Hmh91R()
//        let memberLever = Defaults[\.memberLevel]
//        if memberLever<2{ //后取消该限制
//            self.view.Qianli_Toast(LocalizedString("Upgrade to Premium to use Global Mode!")) //需升级为高级会员后，才能使用全局模式！
//            return
//        }
        let switchBarWidth = 40.0
        let switchBarHeight = 24.0
        let imode = Qianli_G_SharedMdb.shared.GetTunMode()
        if ("global"==imode){
            Qianli_G_SharedMdb.shared.SetTunMode(mode: "rule")
            self.Hvq8YW7v25bbqUMo.setTitleColor(.label, for: .normal)
            self.QuV46HvbGc1uLhUB.setTitleColor(.secondaryLabel, for: .normal)
            self.F04Jpss3hC2aRHCt.frame = CGRect(x: 0, y: 0, width: switchBarHeight, height: switchBarHeight)
        }else{
            Qianli_G_SharedMdb.shared.SetTunMode(mode: "global")
            self.Hvq8YW7v25bbqUMo.setTitleColor(.secondaryLabel, for: .normal)
            self.QuV46HvbGc1uLhUB.setTitleColor(.label, for: .normal)
            self.F04Jpss3hC2aRHCt.frame = CGRect(x: switchBarWidth-switchBarHeight, y: 0, width: switchBarHeight, height: switchBarHeight)
        }
        if QianliVpnManager.shared.vpnStatus == .connected{
            Task{
                await QianliVpnManager.shared.y4On03TpAsKs4W4W(msg: "ChangeMode")
            }
        }
    }
    
    private func wzcHUlL8Lg0ior5o(){
        if let alertBgView = self.DzKXzGjYZ3Z78P0n{
            alertBgView.isHidden = true
            for persub in alertBgView.subviews{
                persub.removeFromSuperview()
            }
            alertBgView.removeFromSuperview()
        }
        self.DzKXzGjYZ3Z78P0n = nil
    }
    
    private func uddQ1zBtVYANiaui(msg:String,btnBT:String){
        wzcHUlL8Lg0ior5o()
        
        self.DzKXzGjYZ3Z78P0n = UIView(frame: CGRect(x: 0, y: 0, width: qianli_pm_width, height: qianli_pm_height))
        if let alertBgView = self.DzKXzGjYZ3Z78P0n{
            self.view.addSubview(alertBgView)
            alertBgView.backgroundColor = .black.withAlphaComponent(0.5)
            
            let alertHeight = 220.0
            let alertWorkView = UIView(frame: CGRect(x: qianli_pm_width/2-300/2, y: qianli_pm_height/2-alertHeight/2-50, width: 300, height: alertHeight))
            alertBgView.addSubview(alertWorkView)
            alertWorkView.backgroundColor = .secondarySystemBackground
            alertWorkView.layer.cornerRadius = 20
            alertWorkView.alpha = 0
            
            let titleLabel = UILabel(frame: CGRect(x: 0, y: 15, width: 300, height: 45))
            alertWorkView.addSubview(titleLabel)
            titleLabel.text = LocalizedString("Friendly Reminder")
            titleLabel.font = .boldSystemFont(ofSize: 15)
            titleLabel.textAlignment = .center
            
            let contentLabel = UILabel(frame: CGRect(x: 15, y:titleLabel.frame.maxY , width: alertWorkView.bounds.width-30, height: alertWorkView.bounds.height-titleLabel.frame.maxY-70))
            alertWorkView.addSubview(contentLabel)
            contentLabel.numberOfLines = 0
            
            let attributedMessage = NSMutableAttributedString(string: msg)
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 10  //设置行间距
            paragraphStyle.alignment = .center

            attributedMessage.addAttributes([NSAttributedString.Key.paragraphStyle:paragraphStyle,
                                             NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15)], range: NSRange(location: 0, length: msg.count))
            contentLabel.attributedText = attributedMessage
            let button = GradientBtn(frame: CGRect(x: alertWorkView.bounds.width/2 - 120/2, y: alertWorkView.bounds.height - 60, width: 120, height: 40),title: btnBT)
            alertWorkView.addSubview(button)
            button.touch_With_Block { [weak self] sender in
                self?.wzcHUlL8Lg0ior5o()
                self?.AQJHyT4esgZZcrFd()
            }
            
            let closeBtn = UIButton(frame: CGRect(x: alertBgView.bounds.width/2 - 24/2, y: alertWorkView.frame.maxY+50, width: 24, height: 24))
            alertBgView.addSubview(closeBtn)
            closeBtn.setImage("qianli_alert_btclose".qianli_R_image, for: .normal)
            closeBtn.touch_With_Block {[weak self] sender in
                self?.wzcHUlL8Lg0ior5o()
            }
            
            UIView.animate(withDuration: 0.25, delay: 0,options: [.curveEaseInOut]) {[weak alertWorkView] in
                alertWorkView?.alpha = 1.0
            }
            
            alertWorkView.tap_With_Block {
                //不做任何操作，只是防止alertBgView点击操作穿透
//                print("防点击穿透")
            }
            
            alertBgView.tap_With_Block {[weak self] in
                self?.wzcHUlL8Lg0ior5o()
            }
        }
        
    }
    
    private func AQJHyT4esgZZcrFd(){
        let memberVC = QianliMemberVC()
        memberVC.modalPresentationStyle = .overFullScreen
        self.present(memberVC, animated: true)
        memberVC.dismissBlock = {[weak self] in
//重新拉取用户信息，
            self?.MuIZuRZXjs2PfsXX()
        }
    }
}

extension QianliCountryVC{
    private func MuIZuRZXjs2PfsXX(){
        self.M62h1bVOydwY8i4y("")
        UserInfoViewModel.shared.MuIZuRZXjs2PfsXX { result in
            DispatchQueue.main.async {[weak self] in
                switch result{
                case .success(let baseData):
                    if baseData.code == 0{
                        self?.IW8gULUFSJCWG7Js("")
                    }else if baseData.code == 40101{
                        self?.flM9woQKzM3ymMZp(baseData.msg)
                    } else{
                        self?.IW8gULUFSJCWG7Js("[\(baseData.code)]\(baseData.msg)")
                    }
                case .failure(let err):
                    self?.IW8gULUFSJCWG7Js(err.localizedDescription)
                }
            }
        }
    }
    
    private func IW8gULUFSJCWG7Js(_ errMsg:String){
        if errMsg.isEmpty{
            //重新拉取订阅信息
            LoginViewModel.shared.PM8lDRSw8vhaZtaq {result in
                DispatchQueue.main.async {[weak self]  in
                    switch result{
                    case .failure(let error):
                        self?.Luxmux9My4MAgvB7("", error.localizedDescription)
                    case .success(let baseData):
                        if baseData.code == 0{
                            self?.Luxmux9My4MAgvB7("", "")
                        }else if baseData.code == 40101{
                            self?.flM9woQKzM3ymMZp(baseData.msg)
                        }else{
                            self?.Luxmux9My4MAgvB7("", "[\(baseData.code)]\(baseData.msg)")
                        }
                    }
                }
            }
        }else{
            view.Qianli_Toast(errMsg)
        }
    }
    
    func Luxmux9My4MAgvB7(_ todo:String,_ errmsg:String){
        self.l0JOXR3PG9RznwqZ()
        if errmsg.isEmpty{
            if let _ = LoginViewModel.shared.customerServiceData{
                //重新拉取节点信息
                 aEasv06wgYeX2ZHn()
            }else{
//                self.l0JOXR3PG9RznwqZ()
                self.view.Qianli_Toast(LocalizedString("Load Subscription Failed. Please retry later!"))//"获取订阅信息失败，请稍后重试！"
            }
        }else{
//            self.l0JOXR3PG9RznwqZ()
            self.view.Qianli_Toast(errmsg)
        }
    }
}

extension QianliCountryVC:UITableViewDelegate, UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.bfLRcdX6OfQEmA24.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "NodeItemCell") as? NodeItemCell//从缓存池中取
        if nil == cell{//如缓存池中没取到，则创建
            cell = UITableViewCell.init(style: .default, reuseIdentifier: "NodeItemCell") as? NodeItemCell
        }
        
        cell!.jHrPakdnRCqvmmiy(title: self.bfLRcdX6OfQEmA24[indexPath.row])
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //直接点击为运行测试该项
        QianliVibrateEnum.selection.L4smXfL531Hmh91R()
        let memberLever = Defaults[\.memberLevel]
        let serverState = Defaults[\.serviceStatus]
        let subState = Defaults[\.subStatus]
        self.Y7sa3i82qEEkE5Uo = self.bfLRcdX6OfQEmA24[indexPath.row]
        
        if memberLever != 2 && indexPath.row>0{
            //判断该节点是否为可选节点
            if LoginViewModel.shared.subscribeNodes.contains(self.Y7sa3i82qEEkE5Uo){
                print("点击可选节点：\(self.Y7sa3i82qEEkE5Uo)")
            }else{
                self.uddQ1zBtVYANiaui(msg: LocalizedString("Upgrade to Premium to use this Node!"), btnBT: LocalizedString("Upgrade Now"))
                //需升级为高级会员后，才能选用线路！
                return
            }
        }
        
//只提示，但还是能选择
        if !serverState{
//            self.view.Qianli_Toast(LocalizedString("Membership has expired. Go to member center renew!"))
            self.uddQ1zBtVYANiaui(msg: LocalizedString("Membership has expired. Go to member center renew!"), btnBT: LocalizedString("Buy Now"))
        }else if !subState{
//            self.view.Qianli_Toast(LocalizedString("Member traffic limit exceeded. Go to member center purchase more!"))
            self.uddQ1zBtVYANiaui(msg: LocalizedString("Member traffic limit exceeded. Go to member center purchase more!"), btnBT: LocalizedString("Buy Now"))
        }
        
        
//选择对应节点，并切换？
        //找当前选中的，取消,然后切换选择
        var isCancel = false
        var lastTitle = Qianli_G_SharedMdb.shared.GetNodeName()
        if let lastNode = Qianli_G_SharedMdb.shared.lastQianliNodeTitle{
            if !lastNode.isEmpty{
                lastTitle = lastNode
            }
        }
        if self.DvET4H5IGpMq3MCT(lastTitle){ //说明上一个是自动线路
            if let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as? NodeItemCell {
                cell.j5WvUB9cdSjK5lw2(false)
            }
            isCancel = true
        }else{
            for (index, strnode) in self.bfLRcdX6OfQEmA24.enumerated() {
                if strnode == lastTitle {
                    if let cell = tableView.cellForRow(at: IndexPath(row: index, section: 0)) as? NodeItemCell {
                        cell.j5WvUB9cdSjK5lw2(false)
                    }//当该cell不在当前可视区显示时，返回nil,此时虽然没有执行到cell.j5WvUB9cdSjK5lw2(false)，但因为cell被复用会自动置为未选择的初始状态
                    isCancel = true
                    break
                }
            }
        }
        
        
        if let cell = tableView.cellForRow(at: indexPath) as? NodeItemCell {
            cell.j5WvUB9cdSjK5lw2(true) //被点击肯定是有cell了
        }
        
        if(!isCancel){
            //没找到，可能是列表变动了，导致没找到当前选中的那个，则全员更新
            self.thrP5dod7I2mzSI0()
            tableView.reloadData()
        }
        
        if QianliVpnManager.shared.vpnStatus == .connected{
            if let loadingHud = self.gbg6hniAI7KHgJ8B{
                loadingHud.hide(animated: true)
                self.gbg6hniAI7KHgJ8B = nil
            }
            self.l0JOXR3PG9RznwqZ()
            
            if indexPath.row == 0{
                self.M62h1bVOydwY8i4y(LocalizedString("Detecting, please wait..."))
                Task{
                    await QianliVpnManager.shared.y4On03TpAsKs4W4W(msg: "QianliAiRouter")
                }
                self.perform(#selector(CSHrk7VkFxzwgVVM), with: nil, afterDelay: 1.5)
            }else{
                self.M62h1bVOydwY8i4y("")
                Task{
                    await QianliVpnManager.shared.y4On03TpAsKs4W4W(msg: "ChangeQianliNode")
                }
                self.perform(#selector(RqyYQOlBUsRqS4TY), with: nil, afterDelay: 1.0)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80.0
    }
    
    private func DvET4H5IGpMq3MCT(_ title:String)->Bool{
        return (title.isEmpty || title == "Qianli.Ai.Router")
    }
    
    private func OjcHtEbQDnL9HsLI(_ msg:String){
        DispatchQueue.main.async {[weak self] in
            if let self = self{
                self.nUuP3Ep6QodYSq6b()
                 
                self.gbg6hniAI7KHgJ8B = MBProgressHUD.showAdded(to: self.view, animated: true)
                if let loadingHud = self.gbg6hniAI7KHgJ8B,!msg.isEmpty{
                    loadingHud.label.text = msg
                }
            }
        }
    }
    
    @objc private func nUuP3Ep6QodYSq6b(){
        if let loadingHud = self.gbg6hniAI7KHgJ8B{
            loadingHud.hide(animated: true)
            self.gbg6hniAI7KHgJ8B = nil
        }
    }
    
    @objc private func CSHrk7VkFxzwgVVM(){
        self.l0JOXR3PG9RznwqZ()
        self.LPq07zWHcZ9thGLm(LocalizedString("Best Router matched!"))
    }
    @objc private func RqyYQOlBUsRqS4TY(){
        self.l0JOXR3PG9RznwqZ()
        if self.Y7sa3i82qEEkE5Uo.isEmpty{
            self.LPq07zWHcZ9thGLm(LocalizedString("Routed Success!"))
        }else{
            let str = LocalizedString("Has Routed to")
            self.LPq07zWHcZ9thGLm("\(str) [\(self.Y7sa3i82qEEkE5Uo)]")
        }
    }
    
}

extension QianliCountryVC{
    private func cUYJyQbeBDg1Ukke(){
        self.M62h1bVOydwY8i4y("")
        let serverId = Defaults[\.serverId]
        LoginViewModel.shared.vFuidwaT3K4CZ0P6(serverId: serverId, completion: {result in
            DispatchQueue.main.async {[weak self]  in
                switch result{
                case .failure(let error):
                    self?.ZHbCZkhcHlscRNOK(error.localizedDescription)
                case .success(let baseData):
                    if baseData.code == 0{
                        self?.ZHbCZkhcHlscRNOK("")
                    }else if(baseData.code == 40101){
                        self?.flM9woQKzM3ymMZp(baseData.msg)
                    } else{
                        self?.ZHbCZkhcHlscRNOK("[\(baseData.code)]\(baseData.msg)")
                    }
                }
            }
        })
        
        if Defaults[\.memberLevel] == 2{
            return
        }
        
        let uuid = Qianli_G_SharedMdb.shared.GetSubUUID()
        guard let homeDir = getSharedDir(udid: uuid,create: true) else{
            self.view.Qianli_Toast("\(LocalizedString("Proxy Node Error，Make sure Login & Retry"))-1")
            self.perform(#selector(clFi25NuDNbscWXL), with: nil, afterDelay: 1.5)
            return
        }
        
        let target = homeDir.appendingPathComponent("config.yaml")
        if !FileManager.default.fileExists(atPath: target.path){
            self.view.Qianli_Toast("\(LocalizedString("Proxy Node Error，Make sure Login & Retry"))-2")
            self.perform(#selector(clFi25NuDNbscWXL), with: nil, afterDelay: 1.5)
            return
        }
        
        if  let yamlString = try? String(contentsOfFile: target.path) {
            do {
                let yaml = try Yams.load(yaml: yamlString) as! [String: Any]
// proxy-groups下type=select的proxies节点组
                if let proxyGroups = yaml["proxy-groups"] as? [[String: Any]] {
                    for group in proxyGroups {
                        if let type = group["type"] as? String {
                            if type == "select"{
                                if let groupName = group["name"] as? String{
                                    Qianli_G_SharedMdb.shared.SetNodeGrop(groupName: groupName)
                                }
                                if let proxies = group["proxies"] as? [String]{
                                    self.bfLRcdX6OfQEmA24.append(LocalizedString("Auto Best Router"))
                                    for proxyName in proxies{
                                        if (proxyName.contains("时间") || proxyName.contains("流量")){
                                            continue
                                        }
                                        self.bfLRcdX6OfQEmA24.append(proxyName)
                                    }
                                }
                                break
                            }
                        }
                    }
                }
                self.thrP5dod7I2mzSI0()
                self.nodeTable.reloadData()
            }
            catch{
                self.view.Qianli_Toast("\(LocalizedString("Proxy Node Error，Make sure Login & Retry"))-3")
                self.perform(#selector(clFi25NuDNbscWXL), with: nil, afterDelay: 1.5)
            }
        }
    }
    
    private func vFuidwaT3K4CZ0P6(){
        self.M62h1bVOydwY8i4y("")
        let serverId = Defaults[\.serverId]
        LoginViewModel.shared.vFuidwaT3K4CZ0P6(serverId: serverId, completion: {result in
            DispatchQueue.main.async {[weak self]  in
                switch result{
                case .failure(let error):
                    self?.ZHbCZkhcHlscRNOK(error.localizedDescription)
                case .success(let baseData):
                    if baseData.code == 0{
                        self?.ZHbCZkhcHlscRNOK("")
                    }else if(baseData.code == 40101){
                        self?.flM9woQKzM3ymMZp(baseData.msg)
                    } else{
                        self?.ZHbCZkhcHlscRNOK("[\(baseData.code)]\(baseData.msg)")
                    }
                }
            }
        })
    }
    
    private func ZHbCZkhcHlscRNOK(_ errmsg:String){
        self.l0JOXR3PG9RznwqZ()
        
        if errmsg.isEmpty{
            
        }else{
            self.view.Qianli_Toast(errmsg)
        }
        
        let memberLever = Defaults[\.memberLevel]
        if memberLever == 2{
            let nodeNames = LoginViewModel.shared.subscribeNodes
            if nodeNames.count>0{
                self.bfLRcdX6OfQEmA24 = nodeNames
                self.bfLRcdX6OfQEmA24.insert(LocalizedString("Auto Best Router"), at: 0)
                self.thrP5dod7I2mzSI0()
                self.nodeTable.reloadData()
                return
            }
        }else if let nodeNames = LoginViewModel.shared.nodeNames{
            self.bfLRcdX6OfQEmA24 = nodeNames
            self.bfLRcdX6OfQEmA24.insert(LocalizedString("Auto Best Router"), at: 0)
            self.thrP5dod7I2mzSI0()
            self.nodeTable.reloadData()
            return
        }
        
        self.view.Qianli_Toast(LocalizedString("Node data not obtained, please try again later"))
    }
    
}


extension QianliCountryVC{
    private func thrP5dod7I2mzSI0(_ isManaul:Bool = true){
        if (!isManaul){
            Qianli_G_SharedMdb.shared.reload()
        }
        let healthStr = Qianli_G_SharedMdb.shared.GetQianliHealthState()
        if !healthStr.isEmpty{
            //aaa:123|bbbb:234|ccc:345
            if let nodeList = healthStr.components(separatedBy: "|") as [String]?{
                LoginViewModel.shared.nodehealthInfo.removeAll()
                for perNode in nodeList{
                    if let nodeInfo = perNode.components(separatedBy: ":") as [String]?{
                        //得到存储到dictionary[aaa] = 123
                        guard nodeInfo.count == 2 else {
                            print("无效的节点格式: \(perNode)")
                            continue
                        }
                        let nodeName = nodeInfo[0].qianli_trim_space()
                        let delayStr = nodeInfo[1].qianli_trim_space()
                        // 验证节点名称不为空且延迟时间可转换为整数
                        guard !nodeName.isEmpty, let delayTime = Int(delayStr) else {
                            print("无效的节点信息: \(perNode)")
                            continue
                        }
                        LoginViewModel.shared.nodehealthInfo[nodeName] = delayTime
                    }
                }
            }
        }
        if isManaul{
            m0GCFZqQS5fY9NUZ()
        }
    }
    
    func ck7imGpVQI5Awo3a(){
        self.thrP5dod7I2mzSI0(false)
    }
    
    private func m0GCFZqQS5fY9NUZ(){
        Task{
            let result = await QianliHealthTester(LoginViewModel.shared.healthNodeList)
            if result.count>0{
                LoginViewModel.shared.nodehealthInfo.removeAll()
                var iFailCount = 0
                for pernode in result{
                    if let nodeInfo = pernode.components(separatedBy: ":") as [String]?{
                        guard nodeInfo.count == 2 else {
                            print("无效的节点格式.cancel: \(pernode)")
                            continue
                        }
                        let nodeName = nodeInfo[0].qianli_trim_space()
                        let delayStr = nodeInfo[1].qianli_trim_space()
                        // 验证节点名称不为空且延迟时间可转换为整数
                        guard !nodeName.isEmpty, let delayTime = Int(delayStr) else {
                            print("无效的节点信息.cancel: \(pernode)")
                            continue
                        }
                        LoginViewModel.shared.nodehealthInfo[nodeName] = delayTime
                        if delayTime==65535{
                            iFailCount += 1
                        }
                    }
                }
                let healthstr = result.joined(separator: "|")
                Qianli_G_SharedMdb.shared.SetQianliHealthState(health: healthstr)
                self.nodeTable.reloadData()
                self.l0JOXR3PG9RznwqZ()
                
                if iFailCount>5 || iFailCount > result.count / 2{
                    
                }
            }else{
                self.l0JOXR3PG9RznwqZ()
            }
        }
    }
    
      private func QpVDhvHgBBwPDzbh(){
        Task{
            await QianliVpnManager.shared.y4On03TpAsKs4W4W(msg: "AllQianliHealth")
            self.ck7imGpVQI5Awo3a()
        }
    }
   
}
